package com.colin.aiyi.ui.Home;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.colin.aiyi.R;
import com.colin.aiyi.adapter.MyFragmentPagerAdapter;
import com.colin.aiyi.app.Constant;
import com.colin.aiyi.entity.User;
import com.colin.aiyi.fragment.HomeFragment;
import com.colin.aiyi.ui.AboutAc;
import com.colin.aiyi.ui.BaseActivity;
import com.colin.aiyi.ui.Home.chudao.ReferrerFragment;
import com.colin.aiyi.ui.Home.mine.HomeFragment2WithNewRefresh;
import com.colin.aiyi.ui.Home.teacherSay.WordFragment2WithNewRefresh;
import com.colin.aiyi.ui.Home.yulu.SentenceFragment2WithNewRefresh;
import com.colin.aiyi.ui.SettingAc;
import com.colin.aiyi.ui.login.LoginAc;
import com.colin.aiyi.ui.pay.PayAc;
import com.colin.aiyi.ui.personal.PersonalAc;
import com.colin.aiyi.utils.AppUtil;
import com.colin.aiyi.utils.MusicUtil;
import com.colin.aiyi.utils.SharePreferenceUtil;
import com.colin.aiyi.utils.TimeUtil;
import com.flyco.tablayout.SlidingTabLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends BaseActivity
        implements View.OnClickListener {

    @BindView(R.id.tool_text)
    TextView toolText;
    @BindView(R.id.tablayout)
    SlidingTabLayout tablayout;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.img_totop)
    ImageView imgTotop;
    @BindView(R.id.img_small)
    ImageView imgSmall;
    @BindView(R.id.text_music_title)
    TextView textMusicTitle;
    @BindView(R.id.seekbar)
    SeekBar seekbar;
    @BindView(R.id.text_music_time)
    TextView textMusicTime;
    @BindView(R.id.img_play)
    ImageView imgPlay;
    @BindView(R.id.img_play_audio)
    ImageView imgPlayAudio;
    @BindView(R.id.text_music_time_sum)
    TextView textMusicTimeSum;
    @BindView(R.id.line_buttom)
    LinearLayout lineButtom;
    @BindView(R.id.circleImageView)
    CircleImageView circleImageView;
    @BindView(R.id.text_username)
    TextView textUsername;
    @BindView(R.id.text_vip)
    TextView textVip;
    @BindView(R.id.text_vip_tag)
    TextView textVipTag;
    @BindView(R.id.text_vip_line)
    LinearLayout textVipLine;
    @BindView(R.id.text_menu1)
    LinearLayout textMenu1;
    @BindView(R.id.text_menu2)
    LinearLayout textMenu2;
    @BindView(R.id.text_menu3)
    LinearLayout textMenu3;
    @BindView(R.id.text_menu4)
    LinearLayout textMenu4;
    @BindView(R.id.text_tuisong)
    TextView textTuisong;

    @BindView(R.id.text_menu5)
    RelativeLayout textMenu5;
    @BindView(R.id.text_shouting)
    TextView textShouting;
    @BindView(R.id.text_menu6)
    RelativeLayout textMenu6;
    @BindView(R.id.text_menu7)
    LinearLayout textMenu7;
    @BindView(R.id.text_menu8)
    LinearLayout textMenu8;
    @BindView(R.id.text_menu9)
    LinearLayout textMenu9;
    @BindView(R.id.text_menu10)
    TextView textMenu10;
    @BindView(R.id.nav_view)
    RelativeLayout navView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.swich_ts)
    CheckBox swichTs;
    @BindView(R.id.swich_st)
    CheckBox swichSt;
    @BindView(R.id.tool_frame)
    FrameLayout toolFrame;

    private MyFragmentPagerAdapter mSectionsPagerAdapter;
    private ArrayList<Fragment> fragmentList;
    private View itemMusic;
    private User user;
    private long firstTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        user = SharePreferenceUtil.getObject(this, User.class);
        ButterKnife.bind(this);
        initView();
        initUserView(user);

        if (getIntent()!=null)
        {
            if (getIntent().getBooleanExtra("isClose",false)){
                finish();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
//        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
//        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        itemMusic = findViewById(R.id.item_music);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawerLayout.setDrawerListener(toggle);
        toggle.syncState();
        initFragment();
        mSectionsPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        viewpager.setOffscreenPageLimit(3);
        viewpager.setAdapter(mSectionsPagerAdapter);
        showFButton(Constant.SHOW_NONE);
//        if (user == null || user.getAccessToken() == null || user.getAccessToken().length() < 1 || !user.isVip()) {
//            textMenu2.setVisibility(View.GONE);
//            textMenu1.setVisibility(View.VISIBLE);
//        } else {
//            textMenu1.setVisibility(View.GONE);
//            textMenu2.setVisibility(View.VISIBLE);
//        }

        tablayout.setViewPager(viewpager);

        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                 MusicUtil.getInstance().pause(seekBar.getProgress());
            }
        });

    }

    private void initUserView(User user) {
        if (isLogin(user)) {
            textUsername.setText(user.getUserName() == null ? "未登录" : user.getUserName());
            textMenu1.setVisibility(View.VISIBLE);
            textMenu2.setVisibility(View.VISIBLE);
            if (user.isVip()) {
//                textMenu1.setVisibility(View.GONE);
//                textMenu2.setVisibility(View.VISIBLE);
                textVipLine.getBackground().setLevel(1);
                textVip.setVisibility(View.VISIBLE);
                textVipTag.setTextColor(getResources().getColor(R.color.c666));
                textVipTag.setText(TimeUtil.getTime(user.getVipStart(), TimeUtil.DATE_FORMAT_DATE_YEAR_M_DOT) +
                        "-" +
                        TimeUtil.getTime(user.getVipEnd(), TimeUtil.DATE_FORMAT_DATE_YEAR_M_DOT));
            } else {
//                textMenu1.setVisibility(View.VISIBLE);
//                textMenu2.setVisibility(View.GONE);
                textVipLine.getBackground().setLevel(0);
                textVip.setVisibility(View.GONE);
                textVipTag.setText("普通会员");
                textVipTag.setTextColor(getResources().getColor(R.color.white));
            }
            if (user.getHeadUrl() != null) {
                Glide.with(getContext()).load(Constant.BASE_URL + user.getHeadUrl()).error(R.mipmap.pic2).into(circleImageView);
            } else {
                if (user.getHeadUrl_local() != null) {
                    try {
                        Glide.with(getContext()).load(new File(user.getHeadUrl())).into(circleImageView);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            textMenu2.setVisibility(View.GONE);
            textMenu1.setVisibility(View.VISIBLE);
        }
        circleImageView.setOnClickListener(this);
        textVipLine.setOnClickListener(this);
        textUsername.setOnClickListener(this);
        swichTs.setChecked(true);
        swichSt.setChecked(true);
        try {
            if (!user.isPush()) {
                swichTs.setChecked(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (!user.isListen()) {
                swichSt.setChecked(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    void initFragment() {
        fragmentList = new ArrayList<>();
   //     fragmentList.add(new WordFragment());
//        fragmentList.add(new SentenceFragment());
//        fragmentList.add(new HomeFragment());
//        fragmentList.add(new ReferrerFragment());

        fragmentList.add(new WordFragment2WithNewRefresh());
        fragmentList.add(new SentenceFragment2WithNewRefresh());
        fragmentList.add(new HomeFragment2WithNewRefresh());
        fragmentList.add(new ReferrerFragment());
    }




    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
//            if (System.currentTimeMillis() - firstTime > 2000) {
//                Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
//                firstTime = System.currentTimeMillis();
//            } else {
//                SharePreferenceUtil.removeObject(this, User.class);
//                finish();
//                System.exit(0);
//            }
        }
    }

    @OnClick({R.id.tool_text, R.id.tool_frame,R.id.img_play, R.id.img_play_audio})
    public void onListenr(View view) {
        switch (view.getId()) {
            case R.id.img_play:
                MusicUtil.getInstance().play();
                break;
            case R.id.img_play_audio:
                MusicUtil.getInstance().stop();
                break;
            case R.id.tool_frame:
            case R.id.tool_text:
                if (drawerLayout.isDrawerOpen(GravityCompat.START))
                    drawerLayout.closeDrawers();
                else
                    drawerLayout.openDrawer(navView);
        }
    }

    @OnClick({R.id.text_menu1, R.id.text_menu2, R.id.text_menu3, R.id.text_menu4, R.id.text_menu5,
            R.id.text_menu6, R.id.text_menu7, R.id.text_menu8, R.id.text_menu9, R.id.swich_ts, R.id.swich_st})
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.text_username:
            case R.id.text_vip_line:
            case R.id.circleImageView:
                if (isLogin(user)) {
                    startActivity(new Intent(this, PersonalAc.class));
                } else {
                    startActivity(new Intent(this, LoginAc.class));
                }
                break;
            case R.id.text_menu1:
            case R.id.text_menu2:
                if (isLogin(user)) {
                    startActivity(new Intent(this, PayAc.class));
                } else {
                    startActivity(new Intent(this, LoginAc.class));
                }

                break;
            case R.id.text_menu3:
                if (user == null || user.getAccessToken() == null || user.getAccessToken().length() < 1) {
                    startActivity(new Intent(this, LoginAc.class));
                    break;
                }
                viewpager.setCurrentItem(2);
                ((HomeFragment) fragmentList.get(2)).setTabSelcect(HomeFragment.HISTORY);
                break;
            case R.id.text_menu4:
                if (user == null || user.getAccessToken() == null || user.getAccessToken().length() < 1) {
                    startActivity(new Intent(this, LoginAc.class));
                    break;
                }
                viewpager.setCurrentItem(2);
                ((HomeFragment) fragmentList.get(2)).setTabSelcect(HomeFragment.LIKE);
                break;
            case R.id.text_menu5:
            case R.id.swich_ts:

                if (swichTs.isChecked()) {
                    user.setPush(true);
                    JPushInterface.resumePush(getApplicationContext());
                } else {
                    user.setPush(false);
                    JPushInterface.stopPush(getApplicationContext());
                }
                ImpPMain.getInstance().user_saveUserInfo(user);
                SharePreferenceUtil.saveObject(this, user);
                break;
            case R.id.text_menu6:
            case R.id.swich_st:
                if (swichSt.isChecked()) {
                    user.setListen(true);
                } else {
                    user.setListen(false);
                }
                ImpPMain.getInstance().user_saveUserInfo(user);
                SharePreferenceUtil.saveObject(this, user);

                break;
            case R.id.text_menu7:
                long csize = AppUtil.getInternalCacheSize(this) + AppUtil.getExternalCacheSize(this);
                AppUtil.cleanExternalCache(this);
                AppUtil.cleanInternalCache(this);
                long csize2 = AppUtil.getInternalCacheSize(this) + AppUtil.getExternalCacheSize(this);
                csize = csize - csize2;
                Toast.makeText(this, "清楚缓存" + csize, Toast.LENGTH_SHORT).show();
                break;
            case R.id.text_menu8:
//                startActivityForResult(new Intent(this, SettingAc.class),0x234);
                if (isLoginWithLogin(user)) {
                    startActivity(new Intent(this, SettingAc.class));
                }
                //startActivity(new Intent(this, SettingAc.class));
                break;
            case R.id.text_menu9:
                startActivity(new Intent(this, AboutAc.class));
                break;
        }
        drawerLayout.closeDrawers();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshHeadView(User user) {
        initUserView(user);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateMusicEvent(MusicUtil.MuiscEvent muiscEvent) {
        switch (muiscEvent.getEventType()) {
            case MusicUtil.MEDIA_STATUS_START:
                Glide.with(this).load(MusicUtil.getInstance().getMusicPic()).error(R.mipmap.pic2).into(imgSmall);
                textMusicTitle.setText("正在缓冲中......");
                textMusicTime.setText("0:00");
                textMusicTimeSum.setText("0:00");
                seekbar.setMax(100);
                seekbar.setProgress(0);
                imgPlay.getBackground().setLevel(0);
                showFButton(Constant.SHOW_MUSIC);
                break;
            case MusicUtil.MEDIA_STATUS_PREPARE:
            case MusicUtil.MEDIA_STATUS_PLAY:
                showFButton(Constant.SHOW_MUSIC);
                Glide.with(this).load(MusicUtil.getInstance().getMusicPic()).into(imgSmall);
                textMusicTitle.setText(MusicUtil.getInstance().getMusicTitle());
                textMusicTime.setText(MusicUtil.getMusicTime(muiscEvent.getMediaPlayer().getCurrentPosition()));
                textMusicTimeSum.setText(MusicUtil.getMusicTime(muiscEvent.getMediaPlayer().getDuration()));
                seekbar.setMax(muiscEvent.getMediaPlayer().getDuration());
                seekbar.setProgress(muiscEvent.getMediaPlayer().getCurrentPosition());
                imgPlay.getBackground().setLevel(1);
                break;
            case MusicUtil.MEDIA_STATUS_PAUSE:
                showFButton(Constant.SHOW_MUSIC_ONLY);
                imgPlay.getBackground().setLevel(0);
                break;
            case MusicUtil.MEDIA_STATUS_STOP:
                showFButton(Constant.HIDE_MUSIC);
                imgPlay.getBackground().setLevel(0);
            case MusicUtil.MEDIA_STATUS_COMLETION:
                showFButton(Constant.HIDE_MUSIC);
                imgPlay.getBackground().setLevel(0);
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==0x586){
            user=SharePreferenceUtil.getObject(this,User.class);
            initUserView(user);
        }
        if (resultCode==0x4444)
        {
            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
           // finish();
//            System.exit(0);
        }
    }

    @Override
    public void showFButton(int level) {
        switch (level) {
            case Constant.SHOW_NONE:
                lineButtom.setVisibility(View.GONE);
                MusicUtil.getInstance().stop();
                break;
            case Constant.SHOW_GOTOP_ONLY:
                lineButtom.setVisibility(View.VISIBLE);
                imgTotop.setVisibility(View.VISIBLE);
                itemMusic.setVisibility(View.GONE);
                MusicUtil.getInstance().stop();
                break;
            case Constant.SHOW_MUSIC_ONLY:
                lineButtom.setVisibility(View.VISIBLE);
                imgTotop.setVisibility(View.GONE);
                itemMusic.setVisibility(View.VISIBLE);
                break;
            case Constant.SHOW_MUSIC:
                lineButtom.setVisibility(View.VISIBLE);
                itemMusic.setVisibility(View.VISIBLE);
                break;
            case Constant.HIDE_MUSIC:
                itemMusic.setVisibility(View.GONE);
                break;
            case Constant.SHOW_ALL:
                lineButtom.setVisibility(View.VISIBLE);
                imgTotop.setVisibility(View.VISIBLE);
                itemMusic.setVisibility(View.VISIBLE);
                break;
        }
    }

}
